﻿package fwk.timer.type
{
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import fwk.timer.TimerAbstract;
	
	public class TimerGlobal extends TimerAbstract
	{
		
		
		private var _timer:Timer;
		private var _stage:Stage;
		private var _modeEnterFrame:Boolean = false;
		
		
		public function TimerGlobal(fps:int = 60) 
		{
			_fps = fps;
			_timer = new Timer(1000 / _fps, 0);
			_timer.addEventListener(TimerEvent.TIMER, onTimerRepeat);
			
		}
		private function onTimerRepeat(evt:TimerEvent):void
		{
			evt.updateAfterEvent();
			
		}
		override public function start():void
		{
			
			if (!_modeEnterFrame) _timer.start();
			
		}
		override public function stop():void
		{
			
			if (!_modeEnterFrame) _timer.stop();
			
		}
		
		override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void 
		{
			if (!_modeEnterFrame) {
				if(_timer != null)
				_timer.addEventListener(TimerEvent.TIMER, listener, useCapture);
			}else {
				if (_stage != null)
				_stage.addEventListener(Event.ENTER_FRAME, listener);
			}
		}
		
		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void 
		{
			if (!_modeEnterFrame) {
				if(_timer != null)
				_timer.removeEventListener(TimerEvent.TIMER, listener, useCapture);
			}else {
				if (_stage != null)
				_stage.removeEventListener(Event.ENTER_FRAME, listener);
			}

			

		}

		override public function set fps(val:int):void
		{
			
			_fps = val;
			_timer.delay = 1000 / _fps;
			
			
		}
				
		
		public function set stage(value:Stage):void 
		{
			_stage = value;
		}
		
		public function get modeEnterFrame():Boolean { return _modeEnterFrame; }
		
		public function set modeEnterFrame(value:Boolean):void 
		{
			_modeEnterFrame = value;
		}
	}
	
}